package com.zxbit.flash.ui.activity.auth;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.zxbit.flash.R;
import com.zxbit.flash.adapter.ContactAdapter;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.AuthRouter;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.common.UserInfo;
import com.zxbit.flash.mvpview.ContactMvpView;
import com.zxbit.flash.mvpview.DictionaryMvpView;
import com.zxbit.flash.presenter.ContactPresenter;
import com.zxbit.flash.presenter.DictionaryPresenter;
import com.zxbit.flash.bean.AuthInfoData;
import com.zxbit.flash.response.AuthInfoResponse;
import com.zxbit.flash.response.BlankResponse;
import com.zxbit.flash.bean.ContactItemInfoData;
import com.zxbit.flash.bean.DictionaryItemData;
import com.zxbit.flash.utils.ToastUtils;
import com.zxbit.flash.view.dialog.MenuDialog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(name = "通讯录认证", path = RouterMap.CONTACT_AUTH_PAGE)
public class ContactAuthActivity extends BaseTitleActivity implements ContactMvpView, DictionaryMvpView {
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    @Autowired(name = Constant.IS_BACK)
    boolean is_back;

    private ContactPresenter contactPresenter;
    private DictionaryPresenter dictionaryPresenter;
    private ContactAdapter adapter;
    private List<AuthInfoData.ContactsInfoBean.ContactsInfosBean> data = new ArrayList<>();
    private ArrayList<DictionaryItemData> dictionaryList;
    private MenuDialog mMenuDialog;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void onUIReady() {
        ARouter.getInstance().inject(this);
        contactPresenter = new ContactPresenter(this);
        dictionaryPresenter = new DictionaryPresenter(this);
        List<String> type = new ArrayList<>();
        type.add("common_relation");
        dictionaryPresenter.getDictionaryData(type);
        LinearLayoutManager lm = new LinearLayoutManager(this);
        rv.setLayoutManager(lm);
        for (int i = 0; i < 5; i++) {
            AuthInfoData.ContactsInfoBean.ContactsInfosBean itemInfo = new AuthInfoData.ContactsInfoBean.ContactsInfosBean();

            data.add(itemInfo);
        }


        adapter = new ContactAdapter(this, data);
        rv.setAdapter(adapter);
        if (UserInfo.isShowUserInformation())
            contactPresenter.getContactInfo();
        if (is_back) {
            tvNextStep.setText(R.string.save_change);
        }
        adapter.setOnSelectRelationListener(new ContactAdapter.OnSelectRelationListener() {
            @Override
            public void onClick(View view, int position) {
                handleDataAndShowDialog((TextView) view);
            }
        });

        adapter.setOnSelectContactListener(new ContactAdapter.OnSelectContactListener() {
            @Override
            public void onClick(View view, int position) {

                selectContact(position);
            }
        });
        rv.smoothScrollToPosition(0);

    }

    public void selectContact(int request) {
        View currentFocus = ((Activity) this).getCurrentFocus();
        if (currentFocus != null) {
            currentFocus.clearFocus();
        }

        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);

        startActivityForResult(intent, request);
    }

    private void handleDataAndShowDialog(TextView edit_text_relation) {
        if (dictionaryList != null && dictionaryList.size() > 0) {
            getMenuDialog().showDialog(edit_text_relation, dictionaryList);
        }
    }

    public MenuDialog getMenuDialog() {
        if (mMenuDialog == null) {
            mMenuDialog = new MenuDialog(this, R.style.dialog_bottom_full);
        }
        return mMenuDialog;
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_auth_contact;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.contact_auth_contact);
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    @Override
    public void onGetDataNext(BlankResponse response) {
        dismissLoadingView();
        if (response.getStatus() == Constant.HTTP_OK) {
            if (!is_back) {
                AuthRouter.getInstance().jumpNextPager(this, RouterMap.CONTACT_AUTH_PAGE);
            } else {
                finish();
            }
        } else {
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(AuthInfoResponse response) {
        ;
        for (int index = 0; index < response.getData().getContactsInfo().getContactsInfos().size(); index++) {
            AuthInfoData.ContactsInfoBean.ContactsInfosBean info = response.getData().getContactsInfo().getContactsInfos().get(index);

            data.set(index, info);
        }
        dismissLoadingView();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onGetDataNext(ArrayList<ArrayList<DictionaryItemData>> responseWrapper) {
        dictionaryList = responseWrapper.get(0);
    }

    @OnClick(R.id.tv_next_step)
    public void onClick() {
        List<ContactItemInfoData> data = new ArrayList<>();
        for (int i = 0; i < rv.getChildCount(); i++) {

            ContactItemInfoData info = new ContactItemInfoData();
            LinearLayout layout = (LinearLayout) rv.getChildAt(i);
            EditText et_name = layout.findViewById(R.id.etName);
            EditText et_phone = layout.findViewById(R.id.etPhone);
            TextView et_relation = layout.findViewById(R.id.etRelation);
            String name = et_name.getText().toString().trim();
            String phone = et_phone.getText().toString().trim();
            String relation = (String) et_relation.getTag();
            if (TextUtils.isEmpty(name)) {
                ToastUtils.showShort(this, getString(R.string.contact_auth_name_toast));
                return;
            } else if (TextUtils.isEmpty(phone)) {
                ToastUtils.showShort(this, getString(R.string.contact_auth_phone_toast));
                return;
            } else if (TextUtils.isEmpty(relation)) {
                ToastUtils.showShort(this, getString(R.string.contact_auth_relation_toast));
                return;
            }
            info.setOrderNo(i + 1 + "");
            info.setUserName(et_name.getText().toString());
            info.setMobile(et_phone.getText().toString());
            info.setRelation((String) et_relation.getTag());

            data.add(info);
        }

        Set<String> set = new HashSet<>();
        for (ContactItemInfoData itemInfo : data) {
            set.add(itemInfo.getMobile());
        }
        if (set.size() == 5) {
            contactPresenter.saveContact(data);
            showLoadingView();

        } else {
            ToastUtils.showShort(this, getString(R.string.contact_auth_contact_repeat));
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && (requestCode >= 0 && requestCode <= 4)) {
            Uri uri = data.getData();
            if (uri != null) {
                boolean isOPPO = false;
                Cursor cursor = null;
                try {
                    cursor = getContentResolver().query(uri, new String[]{ContactsContract
                            .CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone
                            .DISPLAY_NAME}, null, null, null);
                    boolean moveToNext = cursor.moveToNext();
                    if (moveToNext) {
                        String number = cursor.getString(0);
                        String name = cursor.getString(1);
                        if (checkContactRepeat(number)) {
                            AuthInfoData.ContactsInfoBean.ContactsInfosBean itemInfo =
                                    getItemData(requestCode);
                            itemInfo.setMobile(number);
                            itemInfo.setUserName(name);
                            this.data.set(requestCode, itemInfo);
                            adapter.notifyItemChanged(requestCode);
                        } else {
                            ToastUtils.showShort(this, getString(R.string
                                    .contact_auth_contact_repeat));
                        }
                    } else {
                        isOPPO = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    isOPPO = true;
                } finally {
                    if (cursor != null && !cursor.isClosed()) {
                        cursor.close();
                    }
                }
                if (isOPPO) {
                    adapter.setModel(true);
                    ToastUtils.showShort(this, getString(R.string.contact_auth_phone_toast));
                }
            }
        }
    }

    public boolean checkContactRepeat(String number) {
        List<ContactItemInfoData> data = new ArrayList<>();
        for (int i = 0; i < rv.getChildCount(); i++) {

            LinearLayout layout = (LinearLayout) rv.getChildAt(i);
            EditText et_phone = layout.findViewById(R.id.etPhone);
            String phone = et_phone.getText().toString().trim();
            if (number.equals(phone)) return false;

        }

        return true;
    }

    public AuthInfoData.ContactsInfoBean.ContactsInfosBean getItemData(int position) {
        AuthInfoData.ContactsInfoBean.ContactsInfosBean info = new AuthInfoData.ContactsInfoBean.ContactsInfosBean();
        if (rv.getChildCount() - 1 >= position) {
            LinearLayout layout = (LinearLayout) rv.getChildAt(position);
            EditText et_name = layout.findViewById(R.id.etName);
            EditText et_phone = layout.findViewById(R.id.etPhone);
            TextView et_relation = layout.findViewById(R.id.etRelation);
            String name = et_name.getText().toString().trim();
            String phone = et_phone.getText().toString().trim();
            String relation = (String) et_relation.getTag();
            String relationValue = et_relation.getText().toString().trim();
            info.setMobile(phone);
            info.setUserName(name);
            info.setOrderNo(position + 1 + "");
            info.setRelation(relation);
            info.setRelationValue(relationValue);

        }

        return info;
    }


}
